//
//  ChangeWorkareaVC.m
//  Cunli
//
//  Created by lilubin on 15/6/30.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "ChangeWorkareaVC.h"
#import "MyDataService.h"
#import "Config.h"
#import "NSString+MD5.h"
#import "User.h"

#define kUIScreenWidth [UIScreen mainScreen].bounds.size.width
#define kUIScreenHeight [UIScreen mainScreen].bounds.size.height

@interface ChangeWorkareaVC () <UIPickerViewDelegate, UIPickerViewDataSource>
@property (weak, nonatomic) IBOutlet UITextField *workareaField;

@property (nonatomic, strong) NSArray *provinceData;
@property (nonatomic, strong) NSArray *cityData;
@property (nonatomic, strong) UIPickerView *cityPickerView;
@property (nonatomic, strong) NSString *userWorkareaIDs;

@end

@implementation ChangeWorkareaVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"地址";
    [self loadProvinceData];
    
    /*
    if ([CLUser shareCLUser].workareaname != nil) {
        _workareaField.text = [CLUser shareCLUser].workareaname;
    }
    */
    
    if ([Login curLoginDetailUser].workareaname != nil) {
        _workareaField.text = [Login curLoginDetailUser].workareaname;
    }
    
    _cityData = [NSArray array];
    _provinceData = [NSArray array];
    
    _cityPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(20, kUIScreenHeight - 200, kUIScreenWidth-40, 280)];
    _cityPickerView.delegate = self;
    _cityPickerView.dataSource = self;
    _cityPickerView.backgroundColor = [UIColor clearColor];
    
    _workareaField.inputView = _cityPickerView;
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 65, 30);
//    [rightBtn setBackgroundImage:[UIImage imageNamed:@"regnext"] forState:UIControlStateNormal];
    [rightBtn setTitle:@"确认" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(commitAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    UIBarButtonItem *flexSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
    flexSpacer.width = flexSpacer.width - 20;
    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:flexSpacer, rightBarItem, nil]];
    
}

- (void)commitAction:(UIButton *)button
{
    [self.view endEditing:YES];
    if (_userWorkareaIDs.length != 0) {
        NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:4];
        [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
        if ([[_userWorkareaIDs substringFromIndex:_userWorkareaIDs.length-1] isEqualToString:@","])
        {
            [CheckParams setObject:[_userWorkareaIDs substringToIndex:_userWorkareaIDs.length-1] forKey:@"value"];
        }
        else
        {
            [CheckParams setObject:_userWorkareaIDs forKey:@"value"];
        }
        
        [CheckParams setObject:@"workareaid" forKey:@"field"];
        
        NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
        [CheckParams setObject:resultSign forKey:@"sign"];
//        NSLog(@"Work area ids:%@", CheckParams);
        
        [MyDataService requestURL:@"edit_profile.php" httpMethod:@"POST" params:CheckParams fileDatas:nil complection:^(id result) {
            NSLog(@"edit_profile:%@", result);
            if ([result[@"response"] isEqualToString:@"edit_profile"]) {
//                [CLUser shareCLUser].workareaname = _workareaField.text;
                [Login curLoginDetailUser].workareaname = _workareaField.text;
                [self.navigationController popViewControllerAnimated:YES];
            }
        } failureAction:^{
            [Config showHUDWithText:@"工作地点修改失败" andImage:@"error"];
        }];
    }
}

#pragma mark - UIPickerView delegate
//指定列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 2;
}

//指定每列的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0 ) {
        return self.provinceData.count;
    }
    if (component == 1)
    {
        return self.cityData.count;
    }
    return 1;
}

//获取省份，城市名称

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == 0) {
        //显示省份名称
        NSDictionary *dic = self.provinceData[row];
        NSString *proName = dic[@"areaname"];
        
        return proName;
    }
    if (component == 1) {
        if (_cityData.count != 0) {
            NSDictionary *cityDic = self.cityData[row];
            NSString *cityName = cityDic[@"areaname"];
            NSString *cityID = cityDic[@"areaid"];
            
            NSInteger selProvince = [pickerView selectedRowInComponent:0];
            NSDictionary *provinceDic = self.provinceData[selProvince];
            NSString *provinceName = provinceDic[@"areaname"];
            NSString *provinceID = provinceDic[@"areaid"];
            
            _userWorkareaIDs = [NSString stringWithFormat:@"%@,%@", provinceID, cityID];
            _workareaField.text = [provinceName stringByAppendingString:cityName];
            return cityName;
        }
    }
    
    return @"";
    
}

//选中某一行的协议方法
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    //根据选中的省份来确定第二列的显示
    
    _userWorkareaIDs = [NSString string];
    if (component == 0) {
        NSDictionary *provinceDic = self.provinceData[row];
        NSString *provinceName = provinceDic[@"areaname"];
        NSString *provinceID = provinceDic[@"areaid"];
        [self loadCityDataWithProvinceID:provinceID];
        NSString *resultStr = [NSString stringWithFormat:@"%@", provinceName];
        _userWorkareaIDs = [NSString stringWithFormat:@"%@,", provinceID];
        _workareaField.text = resultStr;
    }
    else
    {
        if (_cityData.count != 0) {
            NSDictionary *cityDic = self.cityData[row];
            NSString *cityName = cityDic[@"areaname"];
            NSString *cityID = cityDic[@"areaid"];
       
            NSInteger selProvince = [pickerView selectedRowInComponent:0];
            NSDictionary *provinceDic = self.provinceData[selProvince];
            NSString *provinceName = provinceDic[@"areaname"];
            NSString *provinceID = provinceDic[@"areaid"];
            
            _userWorkareaIDs = [NSString stringWithFormat:@"%@,%@", provinceID, cityID];
            _workareaField.text = [provinceName stringByAppendingString:cityName];
        }
    }
}

#pragma - mark 请求省数据
- (void)loadProvinceData
{
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:3];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:@"-1" forKey:@"areaid"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    
    [MyDataService requestURL:@"area_all.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        if ([result[@"response"] isEqualToString:@"area_all"])
        {
            _provinceData = result[@"arealist"];
        }
        else
        {
            [Config showHUDWithText:@"地址信息加载失败" andImage:@"error"];
        }
    } failureAction:^{
        [Config showHUDWithText:@"网络错误" andImage:@"error"];
    }];

}

- (void)loadCityDataWithProvinceID:(NSString *)provinceID
{
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:3];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:provinceID forKey:@"areaid"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    
    [MyDataService requestURL:@"area_all.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
//        NSLog(@"CITY DATA:%@", result);
        if ([result[@"response"] isEqualToString:@"area_all"])
        {
            _cityData = result[@"arealist"];
            [_cityPickerView reloadComponent:1];
        }
        else
        {
            [Config showHUDWithText:@"城市信息加载失败" andImage:@"error"];
        }
    } failureAction:^{
        [Config showHUDWithText:@"网络错误" andImage:@"error"];
    }];
}


@end
